package com.apestech.framework.xml.pub;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.apestech.framework.util.FileUtil;
import com.apestech.framework.xml.pub.core.ElementUtil;
import org.xml.sax.SAXException;

public class WriteXml extends ElementUtil {
	
	private Document document;
	private String charset="UTF-8";
	private String xml1="<?xml version=\"1.0\" encoding=\"";
	private String xml2="\"?><YuanYuanSoftware></YuanYuanSoftware>";
	private String xml;


	public WriteXml() {
		xml=xml1+charset+xml2;
	}

	public WriteXml(String fieldName) throws Exception {
		SAXReader reader = new SAXReader();
		try {
			reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
			reader.setValidation(false);
			document = reader.read(new File(fieldName));
		} catch (DocumentException e) {
			throw new Exception(getMessage("load_xml_error","读取XML失败:\r    "+e.getMessage()));
		}
	}

	public void setCharset(String charset){
		xml=xml1+charset+xml2;
		this.charset=charset;
	}
	
	public Element createXml() throws Exception{
		createNewXml();
		return document.getRootElement();
	}

	public void setXml(String xml) {
		if(xml!=null && !"".equals(xml.trim())) this.xml = xml;
	}

	/**
	 * 创建空的XML
	 * @return
	 * @throws Exception
	 */
	private Document createNewXml() throws Exception {
		try {
			document = DocumentHelper.parseText(xml);
			return document;
		} catch (DocumentException e) {
			throw new Exception(getMessage("create_empty_xml_error","创建空白XML失败:\r    "+e.getMessage()));
		}		
	}
	
	/**
	 * XML保存到文件
	 * @param filename String
	 * @throws IOException
	 */
	public void writeXml(String filename) throws Exception {
        OutputFormat xmlFormat = new OutputFormat();
		xmlFormat.setEncoding(charset);
        xmlFormat.setNewlines(true); // 设置换行 
        xmlFormat.setIndent(true);  // 生成缩进  
        xmlFormat.setIndent("    ");  // 使用4个空格进行缩进, 可以兼容文本编辑器  
        FileUtil.createDir(filename);
        XMLWriter writer = new XMLWriter(new FileOutputStream(filename),xmlFormat); 
		writer.write(document);  
		writer.close();  
	}
	
	/**
	 * 获取根字段
	 * @return
	 */
	public Element getRoot(){
		return document.getRootElement();
	}

}
